package com.lcu.wl.modules.sys.controller;

import com.lcu.wl.common.utils.SYSDATA;
import com.lcu.wl.modules.sys.entity.User;
import com.lcu.wl.modules.sys.form.LoginForm;
import com.lcu.wl.modules.sys.service.IUserService;
import com.lcu.wl.modules.sys.service.IUserTokenService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 */
@RestController
public class LoginController extends AbstractController{
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserTokenService iUserTokenService;

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody LoginForm loginForm)throws IOException {
        //获取用户信息
        User user = iUserService.queryByUserName(loginForm.getUsername());

       //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(loginForm.getPassword(),user.getSalt()).toHex())){
            return SYSDATA.error("账号或密码不正确");
        }
        //账号无效
        if (user.getStatus() == 0){
            return SYSDATA.error("账号已无效,请联系管理员");
        }
        //生成token，并保存到数据库
        SYSDATA sysdata = iUserTokenService.createToken(user.getUserId());

        return sysdata;
    }

    /**
     * 退出登录
     */
    @PostMapping("/sys/logout")
    public SYSDATA logout(){
        iUserTokenService.logout(getUserId());
        return SYSDATA.ok();
    }
}
